//
//  UserManager.m
//  DDHuilai
//
//  Created by nianfangge on 16/3/29.
//  Copyright © 2016年 Admin. All rights reserved.
//

#import "UserManager.h"
#import "NetRequest+User.h"

@implementation UserManager
static UserManager* instance = nil;

+ (UserManager*)shareInstance {
    @synchronized(self){
        if (instance==nil) {
            instance = [[UserManager alloc] init];
        }
    }
    return instance;
}

- (id)init{
    self = [super init];
    if (self) {
      
    }
    return self;
}

- (void)saveUserLoginInfo:(UserMode *)user
{
    NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *now = [NSDate date];
    NSString *dateStr=[formatter stringFromDate:now];
    user.lastLoginTime = dateStr;
    _user = user;
    
    [self setUserStatus:ONLINE];
    [self arichiveUserObject:user];
}

#pragma mark ---------获取或者设置模型中的数据-------------
// 设置用户状态
- (void)setUserStatus:(UserStatus)userStatus
{
    _userstatus = userStatus;
}
/**
 *  获取用户Id
 *
 *  @return 返回用户的id
 */
- (NSString *)getUserId {
    //暂时写的
    return @"10000";
    return _user.userId;
}

/**
 *  获取用户手机号
 *
 *  @return 返回用户的手机号
 */
- (NSString *)getMobile {
    return _user.email;
}

/*
 *是否是自己根据userid判断
 */
- (BOOL)isSelf:(NSString *)userid {
    _user = [[UserMode alloc] init];
    _user.userId  =  @"200";//写死
    if ([_user.userId isEqualToString:userid]) {
        return YES;
    }
    return NO;
}

#pragma mark ------user模型归档----------
- (void)arichiveUserObject:(UserMode *)user
{
    NSArray *array;
    NSKeyedUnarchiver *unarchiver;
    
    NSData *_data = [[NSData alloc] initWithContentsOfFile:[FilePathMode getFilePathWithModelKey:@"model"]];
    
    if (!_data) {
        array = [NSArray array];
    }
    else
    {
        //解档辅助类
        unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];
        
        //解档出数据模型User
        //解码并解档出model
        array = [unarchiver decodeObjectForKey:@"user"];
    }
    
    if ([array count] > 0)
    {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:array];
        int flag = -2;
        
        for (int i = 0; i < [mutableArray count]; i++)
        {
            UserMode *userData = mutableArray[i];
            if ([user.userId isEqualToString:userData.userId])
            {
                [mutableArray replaceObjectAtIndex:i withObject:user];
                [mutableArray exchangeObjectAtIndex:0 withObjectAtIndex:i];
                flag = i;
                break;
            }
        }
        
        if (-2==flag)
        {
            [mutableArray insertObject:user atIndex:0];
            [self archiveWithArray:mutableArray];
        }
        else
        {
            [self archiveWithArray:mutableArray];
        }
        
        [unarchiver finishDecoding];
    }
    else
    {
        NSMutableArray *mutableArray= [NSMutableArray array];
        [mutableArray addObject:user];
        [self archiveWithArray:mutableArray];
    }
}

- (void)archiveWithArray:(NSMutableArray *)mutableArray
{
    NSMutableData *data = [[NSMutableData alloc] init];
    //创建归档辅助类
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //编码
    [archiver encodeObject:mutableArray forKey:@"user"];
    //结束编码
    [archiver finishEncoding];
    //写入
    [data writeToFile:[FilePathMode getFilePathWithModelKey:@"model"] atomically:YES];
}


// 获取登录用户信息
- (void)getLoginUserInfo
{
    NSData *_data = [[NSData alloc] initWithContentsOfFile:[FilePathMode getFilePathWithModelKey:@"model"]];
    //解档辅助类
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];
    //解档出数据模型User
    //解码并解档出model
    NSArray *array = [unarchiver decodeObjectForKey:@"user"];
    if ([array count] > 0)
    {
        UserMode *result = array[0];
        _user = result;
        [self setUserStatus:ONLINE];
    }
}

// 修改用户编码模型中的昵称
- (void)changeUserCustNameInCodingData:(NSString *)custName
{
    _user.userName = custName;
    
    NSData *_data = [[NSData alloc] initWithContentsOfFile:[FilePathMode getFilePathWithModelKey:@"model"]];
    //解档辅助类
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];
    //解档出数据模型User
    //解码并解档出model
    NSArray *array = [unarchiver decodeObjectForKey:@"user"];
    if ([array count] > 0)
    {
        UserMode *result = array[0];
        result.userName = custName;
        [self arichiveUserObject:result];
    }
}

// 修改用户头像
- (void)changeUserAvatarInCodingData:(NSString *)avatar
{
  

}

// 登录成功
- (void)loginSuccess:(NSString *)loginName password:(NSString *)passWord
{
    [kUserDefaults setBool:YES forKey:IS_LOGIN];
    [kUserDefaults setObject:loginName forKey:LOGIN_EmailAddress];
    [kUserDefaults setObject:passWord forKey:LOGIN_PASSWord];

    [kUserDefaults synchronize];
    
    // 发送登录成功通知
    [NSNotificationCenter  postSwitchLoginStatusNotification:@{@"Login":[NSNumber numberWithBool:YES]}];
}

// 退出登录
- (NSURLSessionDataTask *)logout
{
    if (_user.loginName.length<1 ) {
        return nil;
    }
    
    // 退出登录该账号
    NSURLSessionDataTask *dataTask = [self logoutAccount:_user.token];
 
    // 清除用户数据
    _user = nil;
    _userDic = nil;

    [self setUserStatus:NO_USER];
    
    [kUserDefaults setBool:NO forKey:IS_LOGIN];
    [kUserDefaults synchronize];
    
    // 置空网络请求
    [self setNilNetRequest];
    
    [NSNotificationCenter postSwitchLogoutStatusNotification:@{@"Login":[NSNumber numberWithBool:NO]}];
    
    return dataTask;
}

// 退出App账号
- (NSURLSessionDataTask *)logoutAccount:(NSString *)token
{
    NSString *newToken = [NSString stringWithFormat:@"%@",token];
    // 退出登录
    NSDictionary *params = @{
                             @"token"  : objectToString(newToken)
                             };
    
    NSURLSessionDataTask *dataTask = [[[NetRequest alloc] init] loginOutDictionary:params success:^(BOOL isSucess) {
        NSLog(@"log out success");
    } fail:^(NSString *error) {
        NSLog(@"log out fail");
    }];
    
    return dataTask;
}


// 置空网络请求单例
- (void)setNilNetRequest
{
    // 网络请求置空
    [[NetRequest sharedInstance] cancelRequest];
}

@end
